import Grid from "@/components/base/Grid"
import { pagePathAtom } from "@/features/business/HomePage_deprecated/atom"
import { resolveAssetImage } from "@/utils/common"
import styled from "@emotion/styled"
import { useAtom, useSetAtom } from "jotai"
import { CSSProperties, useEffect, useMemo, useState } from "react"
import { NavLink, useLocation, useParams } from "react-router-dom"
import { homeGamesAtom } from "@/features/business/HomePage_deprecated/atoms_deprecated"
import { useOpacity } from "../hooks/useOpacity"

const Category = styled.div`
    flex: 1;
    height: 56rem;
    transition: all 0.2s ease-in-out;
    a {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        outline: none;
        user-select: none;
        -webkit-tap-highlight-color: transparent;
        span {
            font-weight: 500;
            opacity: 0.7;
        }
        &.active span {
            font-weight: 700;
            opacity: 1;
        }
    }
`

const CategoryItem = styled.div<{
    active?: boolean
}>`
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
`

const CategoryIcon = styled.img`
    width: 28rem;
    height: 28rem;
    object-fit: cover;
`

const CategoryLabel = styled.div<{ textColor: CSSProperties["color"] }>`
    font-weight: 700;
    font-size: 14rem;
    line-height: 20rem;
    text-align: center;
    vertical-align: middle;
    color: ${({ textColor }) => textColor};
    white-space: nowrap;
    position: relative;
    width: 48rem;
    height: 20rem;
    span {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate3D(-50%, -50%, 0);
    }
`
const order = ["Slot", "Live", "Board Game", "Table Game", "Fishing"]

const icons: Record<string, string> = {
    Slot: resolveAssetImage("pages/HomePage/img_slot.webp"),
    Live: resolveAssetImage("pages/HomePage/img_live.webp"),
    Fishing: resolveAssetImage("pages/HomePage/img_fish.webp"),
    ["Board Game"]: resolveAssetImage("pages/HomePage/img_chess.webp"),
    ["Table Game"]: resolveAssetImage("pages/HomePage/img_chess.webp"),
}

export const CategoryMenu = () => {
    const { categoryId = "" } = useParams<{ categoryId: string }>()
    const [active, setActive] = useState<number>(0)
    const [{ links }] = useAtom(homeGamesAtom)

    const menus = useMemo(() => {
        return [
            {
                name: "For You",
                path: "/",
                icon: resolveAssetImage("pages/HomePage/img_for_you.webp"),
            },
            ...Object.entries(links)
                .filter(([name]) => order.includes(name))
                .sort(([keyA], [keyB]) => order.indexOf(keyA) - order.indexOf(keyB))
                .map(([title]) => ({
                    name: title,
                    path: `/s-game/category/${title}?sort=Popular`,
                    icon: icons[title],
                })),
        ]
    }, [links])

    const { opacity } = useOpacity(1)
    const setCount = useSetAtom(pagePathAtom)
    const location = useLocation()

    useEffect(() => {
        if (!["/s-game/sections/favorite"].includes(location.pathname)) {
            setCount((prev) => ({
                ...prev,
                homeCurrentPath: `${location.pathname}${location.search}`,
            }))
        }
    }, [categoryId, location, setCount])

    return (
        <Category>
            <Grid
                columns={5}
                gap={0}
            >
                {menus.map(({ name, icon, path }, idx) => {
                    let textColor: CSSProperties["color"] = "#fff"
                    if (categoryId === "") {
                        textColor =
                            idx === active
                                ? interpolateColor("#fff", "#131416", opacity)
                                : interpolateColor("#fff", "#69728C", opacity)
                    } else {
                        textColor = idx === active ? "#131416" : "#69728C"
                    }
                    const [pathnameOnly, searchOnly] = path.split('?')
                    const searchString = searchOnly ? `?${searchOnly}` : ''
                    return (
                        <Grid.Item key={`${idx}_${path}_category_menu`}>
                            <NavLink
                                to={`${pathnameOnly}${searchString}`}
                                state={{
                                    from: pathnameOnly,
                                    search: searchString
                                }}
                                className={({ isActive, isPending }) => {
                                    if (isActive) {
                                        setActive(idx)
                                    }
                                    return isPending ? "pending" : isActive ? "active" : ""
                                }}
                            >
                                <CategoryItem
                                    onClick={() => {
                                        setActive(idx)
                                    }}
                                >
                                    {!!icon && (
                                        <CategoryIcon
                                            src={icon}
                                            alt=""
                                        />
                                    )}
                                    {!!name && (
                                        <CategoryLabel textColor={textColor}>
                                            <span>{name}</span>
                                        </CategoryLabel>
                                    )}
                                </CategoryItem>
                            </NavLink>
                        </Grid.Item>
                    )
                })}
            </Grid>
        </Category>
    )
}

/**
 * 在两个颜色之间插值计算中间色（渐变色）
 * @param color1 起始颜色，支持 hex 格式，例如 "#fff" 或 "#ffffff"
 * @param color2 结束颜色，支持 hex 格式，例如 "#000000"
 * @param factor 插值因子，范围 0 ~ 1，表示颜色过渡的百分比
 * @returns 返回一个 rgb 颜色字符串，例如 "rgb(255, 128, 0)"
 */
function interpolateColor(color1: string, color2: string, factor: number): string {
    // 限制 factor 在 0 到 1 范围内，避免异常
    const clamp = (val: number) => Math.max(0, Math.min(1, val))
    factor = clamp(factor)

    /**
     * 将 hex 格式的颜色转换为 RGB 数组
     * 支持 3 位和 6 位 hex 格式
     * @example "#fff" => [255, 255, 255]
     * @example "#112233" => [17, 34, 51]
     */
    const hexToRgb = (hex: string): number[] => {
        hex = hex.replace("#", "")
        // 处理 3 位简写颜色，比如 #abc -> #aabbcc
        if (hex.length === 3) {
            hex = hex
                .split("")
                .map((c) => c + c)
                .join("")
        }
        const bigint = parseInt(hex, 16)
        return [
            (bigint >> 16) & 255, // R
            (bigint >> 8) & 255, // G
            bigint & 255, // B
        ]
    }

    // 解析两个颜色为 RGB 数组
    const rgb1 = hexToRgb(color1)
    const rgb2 = hexToRgb(color2)

    // 计算插值后的 RGB 值
    const result = rgb1.map((c, i) => Math.round(c + factor * (rgb2[i] - c)))

    // 返回标准 RGB 字符串
    return `rgb(${result[0]}, ${result[1]}, ${result[2]})`
}
